<template>
  <div>
    <el-card>
      <el-row :gutter="15">
        <el-col :span="spanValue + 1" @colchange="spanValueChange" style="overflow: auto;transition: width .2s;">
          <el-card class="leftBox" shadow="never" :body-style="{padding: '0px'}">
            <el-collapse v-model="activeName" accordion>
              <el-collapse-item title="节目组" name="1" v-collapseSwitch>
                <div class="selectArea">
                  <el-tree
                    accordion
                    ref="treeone"
                    :data="optionsType"
                    :expand-on-click-node="false"
                    node-key="value"
                    :default-expanded-keys="defaultKeys"
                    :props="{ children: 'children' }"
                    @node-click="handleTypeClick">
                    <span class="custom-tree-node" slot-scope="{ node }">
                      <span :title="node.label" style="margin-right: 30px; width: 42%;text-overflow: ellipsis;overflow: hidden;">
                        <font v-if="node.level === 3" style="color: rgb(35 55 132); font-weight: bold;">{{ node.label }} </font>
                        <font v-else>{{ node.label }}</font>
                      </span>
                      <transition name="el-fade-in">
                        <span v-if="(node.key !== 0 && node.key === pgmgrpCurr.value)">
                          <el-button
                            v-if="node.level === 2"
                            icon="el-icon-plus"
                            style="color: #fff;"
                            type="text"
                            size="mini"
                            title="新增"
                            v-permission="permission.add"
                            @click="dialogInfo.cu = 1">
                          </el-button>
                          <el-button
                            v-if="node.level === 3"
                            icon="el-icon-edit"
                            style="color: #fff;"
                            type="text"
                            size="mini"
                            title="重命名"
                            @click="dialogInfo.cu = 2"
                            v-permission="permission.edit">
                          </el-button>
                          <el-button
                            v-if="node.level === 3"
                            icon="el-icon-copy-document"
                            style="color: #fff;"
                            type="text"
                            size="mini"
                            title="复制"
                             @click="dialogInfo.cu = 3"
                            v-permission="permission.edit">
                          </el-button>
                          <el-button
                            v-if="node.level === 3"
                            icon="el-icon-delete"
                            style="color: #fff;"
                            type="text"
                            size="mini"
                            title="删除"
                            @click="deletePgmgrp"
                            v-permission="permission.del">
                          </el-button>
                      </span>
                      </transition>
                    </span>
                  </el-tree>
                </div>
              </el-collapse-item>
            </el-collapse>
            <el-dialog
              :title="dialogInfo.title"
              :before-close="cancelCU"
              :visible.sync="dialogInfo.cu > 0"
              width="420px"
              :close-on-click-modal="false">
              <el-form :model="pgmgrpform" :rules="pgmgrpformRules" ref="pgmgrpformRef" label-width="90px">
                <el-form-item label="节目组名称" prop="pgmgrp_name">
                  <div class="elInputS">
                    <el-input v-model="pgmgrpform.pgmgrp_name"></el-input>
                  </div>
                </el-form-item>
              </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button type="text" @click="cancelCU">取消</el-button>
                <el-button :loading="dialogInfo.cu === 4" type="primary" @click="submitCU">确认</el-button>
              </div>
            </el-dialog>
          </el-card>
        </el-col>
        <el-col :span="(24 - (spanValue + 1))" style="transition: width .2s;">
          <el-row :gutter="20" style="box-shadow: none !important;">
            <el-col :span="14">
              <el-button
                type="primary"
                v-permission="permission.add"
                icon="el-icon-plus"
                @click="innerdialogVisible = true"
                :disabled="pgmgrpnode === null">素材库</el-button>
              <el-button type="danger" @click="delgrpDetail" v-permission="permission.del" icon="el-icon-delete">删除</el-button>
              <el-button
                type="success"
                icon="el-icon-check"
                v-if="grplistSave !== false"
                @click="addgrpoupmats">
                保存
              </el-button>
              <!-- 封装的素材弹窗组件 prop:
                :innerVisible  // 控制弹窗隐藏显示
                v-model        // 接收返回的素材对象
                @change        // 选中素材改变点击确定后的回调事件.
                @close         // 弹窗点击关闭的回调事件，用于告知父组件，由父控制关闭或显示
                mattype        // 接收3个参数（'all', 'adv', 'pgm'） 默认参数为all
              -->
              <mat-dialog
                :innerVisible="innerdialogVisible"
                v-model="matSelectRows"
                mattype="pgm"
                :multify="true"
                :drawerShow="true"
                :replaceBtn="false"
                @dragchange="matSelectChange"
                @close="listenClose">
              </mat-dialog>
            </el-col>
            <el-col :span="10" style="float: right; text-align: right;">
              <table-tools
                :drawerSearch="drawerVisible"
                @searchchange="searchChange"
                @refreshclick="refreshClick">
              </table-tools>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <!-- 列表区域 -->
              <el-table
                @sort-change="handleSortChange"
                @selection-change="handleSelectionChange"
                @row-contextmenu="mouseRightUp"
                row-key="seq"
                v-loading="loading"
                height="75vh"
                ref="table"
                highlight-current-row
                :data="matlists"
                lazy
                border
                stripe
                style="width: 100%;">
                <el-table-column :selectable="checkboxT" type="selection" width="55" />
                <el-table-column prop="seq" label="序号" width="80px" sortable="custom"></el-table-column>
                <el-table-column prop="mat_name" label="素材" show-overflow-tooltip></el-table-column>
                <el-table-column prop="file_len" label="素材长度" show-overflow-tooltip>
                  <template v-slot="scope">
                    <time-picker inputType="readonly" v-model="scope.row.file_len" />
                  </template>
                </el-table-column>
                <el-table-column prop="markin" label="入点">
                  <template v-slot="scope">
                    <time-picker inputType="readonly" v-model="scope.row.markin" />
                  </template>
                </el-table-column>
                <el-table-column prop="markout" label="出点">
                  <template v-slot="scope">
                    <time-picker inputType="readonly" v-model="scope.row.markout" />
                  </template>
                </el-table-column>
              </el-table>
              <el-dropdown @command="handleCommand" trigger="click" id="floatmousebox" ref="dropmenu" placement="bottom-start">
                <span class="el-dropdown-link"></span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="copy" icon="el-icon-document-copy">复制</el-dropdown-item>
                  <el-dropdown-item command="write" icon="el-icon-document-add">粘贴</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script>
import Sortable from 'sortablejs'
import commonMethods from '@/utils/commonMethods.js'
import { pgmInfoConfig } from '@/sysconfig.js' // 引入节目库系统配置
import { lists, add, channelGroup, channelGroupAdd, channelGroupEdit, channelGroupDel } from '@/api/pgmmanage/pgmgroup.js' // 频道列表接口

// 引入已封装好的增删改查相关组件
import tableTools from '@/components/tableToolsComponents' // tabs工具栏组件
import MatDialog from '@/components/MatdialogComponents.vue' // 素材列表弹窗组件

export default {
  name: 'grouplib',
  mixins: [commonMethods],
  components: { tableTools, MatDialog },
  provide() {
    return {
      editroom: this
    }
  },
  filters: {
    subTimeDate: function(value) {
      if (value !== null && value.length > 10) {
        return value.substr(0, 10)
      }
      return value
    }
  },
  watch: {
    'dialogInfo.cu' (newValue, oldValue) {
      if (newValue === 1) {
        this.dialogInfo.title = '新增节目组'
        this.pgmgrpform.channel_id = this.pgmgrpCurr.value
      } else if (newValue === 2) {
        this.dialogInfo.title = '重命名节目组'
        this.$set(this.pgmgrpform, 'pgmgrp_name', this.pgmgrpCurr.label)
        this.pgmgrpform.pgmgrp_id = this.pgmgrpCurr.value
        delete this.pgmgrpform.channel_id
      } else if (newValue === 3) {
        this.dialogInfo.title = '复制节目组'
        this.$set(this.pgmgrpform, 'pgmgrp_name', this.pgmgrpCurr.label)
        this.pgmgrpform.channel_id = this.pgmgrpCurr.pid
      }
    },
    'matlists' () {
      this.grplistSave = true
      this.$nextTick(() => { // 再拖动结束视图更新后，立即对列表序号进行重新排序。
        this.matlists.map((item, index) => {
          this.$set(item, 'seq', index + 1)
        })
      })
    },
    'pgmgrpnode' (newValue, oldValue) {
      if (newValue === null) return
      this.getgrpDetail()
    }
  },
  data() {
    return {
      /* 设置页面权限 */
      permission: {
        add: ['admin', 'grouplib::add'],
        edit: ['admin', 'grouplib::edit'],
        del: ['admin', 'grouplib::del']
      },
      rules: {}, // 表单验证规则
      activeName: '1',
      optionsType: [
        {
          label: '节目组',
          value: 0,
          children: []
        }
      ],
      queryInfo: {}, // 列表查询参数
      loading: false,
      drawerVisible: true,
      grplistSave: false, // 列表变化状态保存按钮置为disabled
      pgmInfoConfig, // 节目库系统配置
      channelList: [], // 频道列表
      rowscurrent: null,
      innerdialogVisible: false,
      matSelectRows: null,
      dialogInfo: {
        title: '新增节目组信息',
        cu: 0
      },
      handleCheckboxRows: [],
      matlists: [],
      pgmgrpnode: null,
      pgmgrpCurr: {},
      pgmgrpform: {},
      pgmgrpformRules: {},
      defaultKeys: [0],
      handleCurrentRow: {}, // 当前单选选中的rows对象
      copyhandlerows: null,
      dragInsetIndex: undefined // 素材拖拽下标
    }
  },
  async created() {
    document.oncontextmenu = function (event) {
      // 阻止页面浏览器右键菜单事件
      event.preventDefault()
    }
    // console.log(this.pgmInfoConfig)
    // 获取节目类型菜单
    this.getmatTypeList()
    console.log(this.channelList)
  },
  mounted() {
    this.setSort()
  },
  async beforeRouteLeave(to, from, next) {
    if (this.grplistSave) {
      const confirmresult = await this.$confirm('列表已修改现在要保存吗？', '提示', {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning'
      }).catch(err => err)
      if (confirmresult !== 'confirm') {
        next()
      }
      this.addgrpoupmats()
      // 是的话 则保存后弹出保存成功提示再确定离开页面。
      next()
    }
    next()
  },
  methods: {
    setSort() {
      const el = this.$refs.table.$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0]
      this.sortable = Sortable.create(el, {
        group: {
          name: 'shared',
          pull: 'clone'
        },
        animation: 150,
        ghostClass: 'sortable-ghost',
        setData: function(dataTransfer) {
          dataTransfer.setData('Text', '')
        },
        onEnd: evt => {
          const targetRow = this.matlists.splice(evt.oldIndex, 1)[0]
          this.matlists.splice(evt.newIndex, 0, targetRow)
          console.log(this.matlists)
        },
        onAdd: (evt) => {
          this.dragInsetIndex = evt.newIndex
          evt.item.remove()
        }
      })
    },
    getmatTypeList() {
      channelGroup().then(res => {
        if (res.status !== 200) {
          console.log('频道分组获取失败')
        }
        this.optionsType[0].children = res.data.data
      })
    },
    checkboxT(row, rowIndex) {
      return row.id !== false
    },
    // 监听列表工具栏 刷新点击事件
    refreshClick() {
      // window.location.reload()
      this.getgrpDetail()
    },
    // 列表字段排序触发监听回调
    handleSortChange(column) {
      this.queryInfo.ordername = column.prop
      this.queryInfo.order = column.order
      console.log(column)
      this.getgrpDetail()
    },
    // 监听列表工具搜索change事件
    searchChange(val) {
      this.drawerVisible = val
    },
    // 按广告类型查看
    async handleTypeClick(data, node, el) {
      if (this.grplistSave) {
        const confirmresult = await this.$confirm('列表已修改现在要保存吗？', '提示', {
          confirmButtonText: '是',
          cancelButtonText: '否',
          type: 'warning'
        }).catch(err => err)
        if (confirmresult === 'confirm') {
          this.addgrpoupmats()
        }
        // 是的话 则保存后弹出保存成功提示再确定离开页面。
      }

      if (this.$refs.treeone.currentNode !== null) {
        this.$refs.treeone.currentNode.$el.setAttribute('class', 'el-tree-node')
      }
      el.$el.setAttribute('class', 'el-tree-node is-current is-focusable') // 设置选中

      this.pgmgrpnode = node.level === 3 ? node : null
      this.pgmgrpCurr = data
      this.pgmgrpCurr.pid = node.parent.key
    },
    listenClose(state) {
      this.innerdialogVisible = state
    },
    // 素材列表弹窗单元行选中返回事件
    matSelectChange(sourceRow) {
      // 统一将接收来的节目转为数组
      const Targetdata = []
      if (sourceRow instanceof Array) { // 返回的是数组形式
        for (const item of sourceRow) {
          Targetdata.push({
            mat_id: item.mat_id,
            mat_name: item.mat_name,
            file_len: item.file_len,
            markin: item.markin,
            markout: item.markout,
            pgmgrp_id: this.pgmgrpnode.key
          })
        }
      } else {
        Targetdata[0] = {
          mat_id: sourceRow.mat_id,
          mat_name: sourceRow.mat_name,
          file_len: sourceRow.file_len,
          markin: sourceRow.markin,
          markout: sourceRow.markout,
          pgmgrp_id: this.pgmgrpnode.key
        }
      }

      if (this.dragInsetIndex === undefined) { // 按钮点击方式
        const _tmpindex = this.matlists.indexOf(this.handleCurrentRow) // 查看父列表 是否选中节点
        _tmpindex > -1 ? this.matlists.splice(_tmpindex, 0, ...Targetdata) : this.matlists.push(...Targetdata)
      } else { // 拖拽方式
        this.matlists.splice(this.dragInsetIndex, 0, ...Targetdata)
      }

      this.dragInsetIndex = undefined // 重置事件
    },
    getgrpDetail() {
      if (this.pgmgrpnode.key === undefined) return
      // 查询节目组下素材列表信息
      this.loading = true
      this.queryInfo.type = this.pgmgrpnode.key
      lists(this.queryInfo).then(res => {
        setTimeout(() => {
          this.loading = false
          if (res.status !== 200) return
          this.matlists = res.data.data.list
          this.grplistSave = false
          this.$nextTick(() => {
            this.grplistSave = false
          })
        }, 150)
      })
    },
    // 向节目组下添加素材
    addgrpoupmats() {
      if (this.matlists.length < 1) return
      const matid_str = this.matlists.map((item, index) => {
        return item.mat_id
      }).join()
      const data = {
        pgmgrp_id: this.pgmgrpnode.key,
        mat_id: matid_str
      }
      add(data).then(res => {
        if (res.status !== 200) return
        this.grplistSave = false
        this.$notify({
          title: '保存成功',
          message: '节目组素材添加成功！',
          type: 'success'
        })
        this.getgrpDetail()
      })
    },
    // 取消
    cancelCU() {
      this.dialogInfo.cu = 0
      this.pgmgrpform = {}
    },
    submitCU() {
      if (this.dialogInfo.cu === 1 || this.dialogInfo.cu === 3) { // 新增, 复制
        channelGroupAdd(this.pgmgrpform).then(res => {
          if (res.status === 200) {
            this.getmatTypeList()
            this.$message.success('新增成功')
            this.defaultKeys = [this.pgmgrpform.channel_id]
          }
          this.dialogInfo.cu = 0
        })
      } else {
        channelGroupEdit(this.pgmgrpform).then(res => {
          if (res.status === 200) {
            this.getmatTypeList()
            this.$message.success('编辑成功')
            this.defaultKeys = [this.pgmgrpform.pgmgrp_id]
          }
          this.dialogInfo.cu = 0
        })
      }
    },
    async deletePgmgrp() {
      const confirmresult = await this.$confirm('是否删除节目组`' + this.pgmgrpCurr.label + '` ，是否确定？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmresult !== 'confirm') {
        return this.$message.info('您已取消了删除')
      }
      const ids = [this.pgmgrpCurr.value]
      channelGroupDel(ids).then(res => {
        if (res.data.data.code !== 1) {
          return this.$message.error('删除失败')
        }
        this.$message.success('删除成功')
        this.getmatTypeList()
        this.defaultKeys = [this.pgmgrpCurr.pid]
      })
    },
    async delgrpDetail() {
      if (this.handleCheckboxRows.length < 1) {
        return this.$alert('请至少选中一条节目！', '', {
          confirmButtonText: '确定',
          type: 'error',
          callback: function() {
            console.log('close1')
          }
        })
      }
      const confirmresult = await this.$confirm('是否删除当前选中节目组`' + this.pgmgrpCurr.label + '` 下节目信息 ，是否确定？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmresult !== 'confirm') {
        return this.$message.info('您已取消了删除')
      }

      const newData = this.matlists.filter(item => { // 获取当前节目组中新数组
        if (this.handleCheckboxRows.indexOf(item) === -1) {
          return item
        }
      })

      const matid_str = newData.map(item => {
        return item.mat_id
      }).join()

      const data = {
        pgmgrp_id: this.pgmgrpnode.key,
        mat_id: matid_str
      }

      add(data).then(res => {
        if (res.status !== 200) return
        this.grplistSave = false
        this.$notify({
          title: '删除成功',
          message: '节目删除成功！',
          type: 'success'
        })
        this.getgrpDetail()
      })
    },
    // 监听table列表多选checkbox多选变化事件
    handleSelectionChange(select) {
      this.handleCheckboxRows = select || []
    },
    // 列表操作栏下拉菜单指令触发方法
    handleCommand(commond) {
      switch (commond) {
        case 'copy':
          this.copyhandlerows = this.handleCurrentRow // 创建新的对象保存
          break
        case 'write':
          var copyrows = JSON.parse(JSON.stringify(this.copyhandlerows))
          delete copyrows.seq
          this.matlists.splice((this.handleCurrentRow.seq), 0, copyrows)
          break
      }
    },
    // 当表格单元行被鼠标右键点击时触发事件
    mouseRightUp(row, column, event) {
      this.$refs.dropmenu.visible = false
      this.$refs.table.setCurrentRow(row) // 用于单选表格，设定单元行为选中行

      // 设定操作栏浮窗相对页面位置,并显示ss。
      const dom = document.getElementById('floatmousebox')
      dom.style.left = event.clientX + 20 + 'px'
      dom.style.top = event.clientY + 'px'
      this.$refs.dropmenu.show()

      this.handleCurrentRow = row // 缓存当前右键选中行
    }
  }
}
</script>

<style lang="less" scoped>
  .el-form-item {
    margin-bottom: 3px !important;
  }
  .operator {
    float: right;
    display: inline-block;
    margin-left: 20px;
  }
  .detailOpera .el-button {
    margin-top: 15px;
  }
  .leftBox {
    height: 81vh;
    background-color: rgba(222, 223, 230, 0.6);
  }
  .footCard {
    border:  1px solid rgba(222, 223, 230, 1);
    margin-top: 10px;
  }
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    font-size: 14px;
  }
  #floatmousebox {
    position: fixed;
  }
</style>
